<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="studentName">
        <el-input v-model="queryParams.studentName" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学校名称" prop="schoolName">
        <el-input v-model="queryParams.schoolName" placeholder="请输入学校名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="年级" clearable style="width: 240px">
          <el-option v-for="grade in gradeOptions" :key="grade.gradeName" :label="grade.gradeName" :value="grade.gradeName" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="性别" clearable>
          <el-option v-for="dict in dict.type.sys_student_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="学员状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:student:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleBatchRegistCourse" v-hasPermi="['system:student:course']" >批量注册课程</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="头像" align="center" prop="avatar">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" class="user-avatar">
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="studentName" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="学校名称" align="center" prop="schoolName" />
      <el-table-column label="手机号" align="center" prop="phonenumber" />
      <el-table-column label="年级" align="center" prop="grade" />
      <el-table-column label="注册日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="expireTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_student_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:student:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleSettings(scope.row)"
            v-hasPermi="['system:student:settings']"
          >学习设置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-notebook-2"
            @click="handleSingleRegistCourse(scope.row)"
            v-hasPermi="['system:student:course']"
          >注册课程</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:student:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入新密码,若不设置可不填写" />
        </el-form-item>
        <el-form-item label="年级">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option v-for="item in gradeOptions" :key="item.gradeName" :label="item.gradeName" :value="item.gradeName" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="expireTime">
          <el-date-picker
            v-model="form.expireTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 学习设置对话框 -->
    <el-dialog title="学习设置" :visible.sync="settingsOpen" width="500px" append-to-body>
      <el-form ref="settingsForm" :model="settingsForm" label-width="120px">
        <el-form-item label="Alpha音乐播放">
          <el-switch v-model="settingsForm.alphaMusicBoolean" />
        </el-form-item>
        <el-form-item label="每组学习单词数">
          <el-input-number v-model="settingsForm.wordsPerGroup" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="最大复习单词数">
          <el-input-number v-model="settingsForm.maxReviewWords" :min="10" :max="100" />
        </el-form-item>
        <el-form-item label="正确单词提示秒数">
          <el-input-number v-model="settingsForm.correctWordTipSeconds" :min="1" :max="10" />
        </el-form-item>
        <el-form-item label="听写时长">
          <el-select v-model="settingsForm.dictationDuration">
            <el-option label="10秒" :value="10" />
            <el-option label="20秒" :value="20" />
            <el-option label="30秒" :value="30" />
            <el-option label="60秒" :value="60" />
            <el-option label="120秒" :value="120" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSettings">确 定</el-button>
        <el-button @click="settingsOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 注册课程对话框 -->
    <el-dialog title="注册课程" :visible.sync="courseOpen" width="500px" append-to-body>
      <el-form ref="courseForm" :model="courseForm" label-width="80px">
        <el-form-item label="课程" prop="courseIds">
          <treeselect v-model="courseForm.courseIds" :options="courseOptions" :disable-branch-nodes="true" :multiple="true" :show-count="true" placeholder="请选择所属单元" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCourse">确 定</el-button>
        <el-button @click="courseOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent, updateSettings, registerCourse, courseTreeSelect, addStudentCourseBatch } from "@/api/system/student";
import { listCourseOfStudent} from "@/api/system/course";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Student",
  dicts: ['sys_normal_disable', 'sys_student_sex'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selectedIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学员表格数据
      studentList: [],
      gradeOptions: [{gradeName: '一年级'}, {gradeName: '二年级'}, {gradeName: '三年级'}, {gradeName: '四年级'}, {gradeName: '五年级'}, {gradeName: '六年级'}, {gradeName: '七年级'}, {gradeName: '八年级'}, {gradeName: '九年级'}],
      // 班级列表
      classList: [],
      // 课程列表
      courseList: [
        {name: 'name1', value: 'value1', id: 'id1', lable: 'label1'},
        {name: 'name2', value: 'value2', id: 'id2', lable: 'label2'}
      ],
      // 所有课程树选项
      courseOptions: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示设置弹出层
      settingsOpen: false,
      // 是否显示课程弹出层
      courseOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classId: null,
        studentName: null,
        realName: null,
        status: null
      },
      // 表单参数
      form: {
        id: null,
        studentName: null,
        realName: null,
        phonenumber: null,
        grade: null,
        expireTime: null,
        password: null,
        status: "0"
      },
      // 学习设置表单
      settingsForm: {
        alphaMusic: 0,
        alphaMusicBoolean: false,
        wordsPerGroup: 10,
        maxReviewWords: 50,
        correctWordTipSeconds: 3,
        dictationDuration: 30
      },
      // 课程表单
      courseForm: {
        type: 'all',
        courseIds: []
      },
      // 表单校验
      rules: {
        studentName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        expireTime: [
          { required: true, message: "有效期不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    // 获取课程
    this.getCourseTree();
  },
  methods: {
    /** 查询学员列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getCourseTree() {
      courseTreeSelect().then(response => {
        this.courseOptions = response.data;
        // this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
        console.log(this.unitOptions);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        studentId: null,
        studentName: null,
        realName: null,
        phonenumber: null,
        expireTime: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.studentId)
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    handleCheckedCourseChange(param) {
      console.log('param---', param);
      console.log('courseForm.courseIds---', this.courseForm.courseIds);

    },
    /** 获取已注册课程列表 */
    getStudentCourseListOfStudent(studentId) {
      listCourseOfStudent(studentId).then(response => {
        this.courseForm.courseIds = response.rows.map(item => item.courseId);
        // this.courseForm.courseIds = [4, 5];
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.formType = 'add';
      this.reset();
      this.open = true;
      this.title = "添加学员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.formType = 'edit';
      this.reset();
      getStudent(row.studentId).then(response => {
        this.form = response.data;
        this.form.password = '';
        this.open = true;
        this.title = "修改学员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formType == 'edit') {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除学员姓名为"' + row.realName + '"的数据项？').then(function() {
        return delStudent(row.studentId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 学习设置操作 */
    handleSettings(row) {
      console.log('row---', row);
      this.settingsForm = {
        studentId: row.studentId,
        alphaMusicBoolean: row.alphaMusic == 1 ? true : false,
        wordsPerGroup: row.wordsPerGroup || 10,
        maxReviewWords: row.maxReviewWords || 50,
        correctWordTipSeconds: row.correctWordTipSeconds || 3,
        dictationDuration: row.dictationDuration || 30
      };
      this.settingsOpen = true;
    },
    /** 提交学习设置 */
    submitSettings() {
      this.settingsForm.alphaMusic = this.settingsForm.alphaMusicBoolean == true ? 1 : 0;
      updateSettings(this.settingsForm).then(response => {
        this.$modal.msgSuccess("设置成功");
        this.settingsOpen = false;
        this.getList();
      });
    },
    /** 注册课程操作 */
    handleSingleRegistCourse(row) {
      this.selectedIds = [row.studentId];
      this.showBatchRegistCourse('single');
    },
    handleBatchRegistCourse() {
      this.selectedIds = this.ids;
      this.showBatchRegistCourse('batch');
    },
    showBatchRegistCourse(type, studentIds) {
      this.courseForm.courseIds = [];
      // this.getCoursesForCheckbox('all');

      if(type == 'single') {
        this.getStudentCourseListOfStudent(this.selectedIds[0]);
      }

      this.courseOpen = true;
    },
    /** 提交课程注册 */
    submitCourse() {
      if (this.courseForm.courseIds.length === 0) {
        this.$modal.msgError("请选择课程");
        return;
      }
      addStudentCourseBatch(this.selectedIds, this.courseForm.courseIds).then(response => {
        this.$modal.msgSuccess("分配成功");
        this.courseOpen = false;
      });
      // registerCourse(this.courseForm).then(response => {
      //   this.$modal.msgSuccess("注册成功");
      //   this.courseOpen = false;
      //   this.getList();
      // });
    }
  }
};
</script>

<style lang="scss" scoped>
.user-avatar {
  cursor: pointer;
  width: 40px;
  height: 40px;
  border-radius: 10px;
}
</style>
